from myapp import setup_logger
from flask import g, jsonify
from flask_jwt_extended import jwt_required, current_user
from myapp.routes import system
from myapp.models import Resource, Organization, ResourceType, SysConfig
from myapp import captcha
from myapp.utils.reposeUtils import ApiResponse
logger = setup_logger(__name__)

def setAccessable(resource, permitedIDList):
    if resource.ID not in permitedIDList:
        resource.HIDDEN = True
    
    for child in resource.children:
        setAccessable(child, permitedIDList)

@system.route('/getRouters')
@jwt_required()
def getRouters():
    resource_ids = set()

    # 从组织获取资源
    for org in current_user.organizations:
        resource_ids.update(res.id for res in org.resources)

    # 从角色获取资源
    for role in current_user.roles:
        resource_ids.update(res.id for res in role.resources)

    # 查询所有顶层资源（parent_id为None）
    top_level_resources = Resource.query.filter(
        Resource.resource_id == None
    ).all()

    # 过滤出用户有权限的资源
    accessible_resources = [
        res for res in top_level_resources
        if res.id in resource_ids
    ]

    return ApiResponse.success(data=[res.to_router_json() for res in accessible_resources])

@system.route('/captchaImage')
def captchaImage():
    showCaptcha = True
    config = SysConfig.query.filter(SysConfig.config_key == 'sys.account.captchaOnOff').first()
    if config and config.config_value == 'false':
        showCaptcha = False
        return jsonify({ 'success': True, 'data': { 'captchaOnOff': showCaptcha, 'img': None, 'uuid': None } })
    else:
        new_captcha_dict = captcha.create()
        return jsonify({ 'success': True, 'data': { 'captchaOnOff': showCaptcha, 'img': new_captcha_dict['img'], 'uuid': new_captcha_dict['hash']} })